package com.hsurosy.trigger.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hsurosy.domain.activity.model.entity.SkuRechargeEntity;
import com.hsurosy.domain.activity.model.valobj.OrderTradeTypeVO;
import com.hsurosy.domain.activity.service.IRaffleActivityAccountQuotaService;
import com.hsurosy.domain.credit.model.entity.TradeEntity;
import com.hsurosy.domain.credit.model.valobj.TradeNameVO;
import com.hsurosy.domain.credit.model.valobj.TradeTypeVO;
import com.hsurosy.domain.credit.service.ICreditAdjustService;
import com.hsurosy.domain.rebate.event.SendRebateMessageEvent;
import com.hsurosy.domain.rebate.model.valobj.RebateTypeVO;
import com.hsurosy.types.enums.ResponseCode;
import com.hsurosy.types.event.BaseEvent;
import com.hsurosy.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-18 17:43
 * @Description 监听用户行为返利消息
 * @Version: v1.0.0
 */
@Slf4j
@Component
public class RebateMessageCustomer {

    @Value("${spring.rabbitmq.topic.send_rebate}")
    private String topic; // RabbitMQ 消息队列主题

    @Resource
    private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService; // 活动账户配额服务
    @Resource
    private ICreditAdjustService creditAdjustService; // 积分调整服务

    /**
     * 监听行为返利消息队列，消费消息并执行对应的奖励处理逻辑
     *
     * @param message 消息内容（JSON 格式）
     */
    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_rebate}"))
    public void listener(String message) {
        try {
            log.info("监听用户行为返利消息 topic: {} message: {}", topic, message);
            // 1. 转换消息：解析消息内容为事件消息对象
            BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage>>() {
            }.getType());
            SendRebateMessageEvent.RebateMessage rebateMessage = eventMessage.getData();

            // 2. 根据返利类型进行处理
            switch (rebateMessage.getRebateType()) {
                case "sku":
                    // 构建活动账户 SKU 充值实体对象
                    SkuRechargeEntity skuRechargeEntity = new SkuRechargeEntity();
                    skuRechargeEntity.setUserId(rebateMessage.getUserId()); // 设置用户ID
                    skuRechargeEntity.setSku(Long.valueOf(rebateMessage.getRebateConfig())); // 设置 SKU 值
                    skuRechargeEntity.setOutBusinessNo(rebateMessage.getBizId()); // 设置业务编号
                    skuRechargeEntity.setOrderTradeType(OrderTradeTypeVO.rebate_no_pay_trade);
                    // 调用活动账户配额服务，创建订单
                    raffleActivityAccountQuotaService.createOrder(skuRechargeEntity);
                    break;
                case "integral":
                    // 构建积分调整实体对象
                    TradeEntity tradeEntity = new TradeEntity();
                    tradeEntity.setUserId(rebateMessage.getUserId()); // 设置用户ID
                    tradeEntity.setTradeName(TradeNameVO.REBATE); // 设置交易名称为返利
                    tradeEntity.setTradeType(TradeTypeVO.FORWARD); // 设置交易类型为正向积分调整
                    tradeEntity.setAmount(new BigDecimal(rebateMessage.getRebateConfig())); // 设置调整积分金额
                    tradeEntity.setOutBusinessNo(rebateMessage.getBizId()); // 设置业务编号
                    // 调用积分调整服务，创建订单
                    creditAdjustService.createOrder(tradeEntity);
                    break;
            }
        } catch (AppException e) {
            // 处理业务异常：忽略唯一索引冲突的重复消费情况
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听用户行为返利消息，消费重复 topic: {} message: {}", topic, message, e);
                return;
            }
            throw e;
        } catch (Exception e) {
            // 捕获其他异常并记录错误日志
            log.error("监听用户行为返利消息，消费失败 topic: {} message: {}", topic, message, e);
            throw e;
        }
    }

}
